<?php
$isReloadable = false;
require_once("../../pers/inc.config.php");
require_once(R2_FS_WEB_ROOT.'/app/_inc/inc.session.php');
require_once(R2_FS_WEB_ROOT.'/app/_inc/funct.html.php');

foreach ($aTipiAttRint as $key => $value) {
	reqDef('tr_'.$key, 'X');
}

if (reqVar('prefile')=='') $_REQUEST['prefile'] = uniqid('pref');

//Gestione azioni
if (reqvar('azione')=='assegnazioneFuoriRint'){$msgPag .= confAss();}

// Dati: assegnazioni attivita' fuori rint.
$sSqlAss = "SELECT * FROM assegnaz WHERE id_comm = ".intval(reqVar('id'))." AND id_rint = 0 ".
           "ORDER BY tipo_att, id_operatore";
$objDB->query($sSqlAss,'selAss');
$aAss = array();
while ($acAss = $objDB->fetch('selAss')) {	
	$aAss[$acAss['tipo_att']][] = $acAss['id_operatore']; 
}

// Dati: array richiedenti.
$sSqlRich = "SELECT * FROM richiedenti WHERE id_comm = ".intval(reqVar('id'));
$objDB->query($sSqlRich,'selRich');
$aRich = array();
while ($acRich = $objDB->fetch('selRich')) {	
	$aRich[] = $acRich['id_operatore']; 
}

// Dati: array clienti.
$sSqlCli = "SELECT * FROM clienti_comm WHERE id_comm = ".intval(reqVar('id'));
$objDB->query($sSqlCli,'selCli');
$aCli = array();
while ($acCli = $objDB->fetch('selCli')) {	
	$aCli[] = $acCli['id_cliente']; 
}

// array clienti
$aCl = array();
$aCl[0] = " - scegliere un cliente - ";
foreach ($aClientiRint as $key => $value) {
	$aCl[$key] = $value['nome'];
}
asort($aCl);

// array responsabili, array operatori e array richiedenti.
$aResp = array();
$aOpe  = array();
$aRic = array();
$aResp[0] = "- scegliere un responsabile - ";
foreach ($aUtentiRint as $key => $value) {
	$aResp[$key] = $value['nome'];
	if ($value['ric_ope'] == 'ope') {
		$aOpe[$key]  = $value['nome'];
	} else {
		$aRic[$key]  = $value['nome'];
	}
}
asort($aResp);
asort($aOpe);
asort($aRic);

if (reqvar('azione')=='salva'){$msgPag .= confComm($aTipiAttRint, array_keys($aAss), $aRic, $aCl);}

// array tipo rilevazione.
$aTipoRilevazione = array();
$aTipoRilevazione['R'] = 'Rint';
$aTipoRilevazione['A'] = 'Attivita\'';
$aTipoRilevazione['X'] = 'Entrambi';

// Dati: commessa selezionata
$sqlSel = " SELECT c.*, a.* ". 
          " FROM commessa c ".
	      " LEFT JOIN att_previste a ON a.id_comm = c.id_comm ".
          "                         AND a.id_rint = 0 ".
          " WHERE c.id_comm = ".intval(reqVar('id'));
$objDB->query($sqlSel,'selRec');
if (!$acRec = $objDB->fetch('selRec')) {
	backOnErr("var. id. '".reqVar('id')."' mancante o errato");
}

//Al primo accesso setto le variabili
if (reqvar('azione')=='') {
		
	$objDB->seekFirst('selRec');
	while ($acRec = $objDB->fetch('selRec')) {	
		$_REQUEST['cod_comm'] = $acRec['cod_comm'];
		$_REQUEST['cod_coge'] = $acRec['cod_coge'];
		$_REQUEST['descr'] = $acRec['descr'];	
		$_REQUEST['data_iniz'] = YMD2DMY($acRec['data_iniz']);	
		$_REQUEST['data_fine'] = YMD2DMY($acRec['data_fine']);
		$_REQUEST['id_cliente'] = $acRec['id_cliente'];
		$_REQUEST['id_responsabile'] = $acRec['id_responsabile'];
		$_REQUEST['ta_'.$acRec['tipo_att']] = $acRec['tipo_att'];	
		$_REQUEST['tr_'.$acRec['tipo_att']] = $acRec['tipo_rilevazione'];		
	}
	
	foreach ($aRich as $ope) {
		$_REQUEST['rc_'.$ope] = $ope;
	}
	
	foreach ($aCli as $cli) {
		$_REQUEST['cl_'.$cli] = $cli;
	}
	
}

if (reqvar('azione')=='assFuoriRint') {
	$_REQUEST['ofr'] = $aAss[reqVar('ta_fr')];	
}

$aTaOpt = array();
$aTaOpt['onClick'] = 'javascript:fuoriRintA(this)';

$aTrOpt = array();
$aTrOpt['onClick'] = 'javascript:fuoriRintR(this)';


$sCmdL  = "";

$sCmdR  = "";
$sCmdR .= "<a class='cmd1' href='#' onclick=\"submAzione('salva');\">conferma</a>";
$sCmdR .= "&nbsp;&nbsp;&nbsp";
$sCmdR .= cmdTorna('annulla');

testaHtml('Modifica commessa', $msgPag);

// Campi nascosti
echo getHtmlForm('frm1');
echo getHtmlHidden('azione','...');
echo getHtmlHidden('prefile');
echo getHtmlHidden('id');
echo getHtmlHidden('ta_fr');
echo getHtmlHidden('xsn',XSN);
?>

<script>
	function submAzione(azione) {
		document.frm1.azione.value=azione;
		document.frm1.submit();
	}
	
	function submFuoriRint(azione, ta) {
		document.frm1.azione.value=azione;
		document.frm1.ta_fr.value=ta; 
		document.frm1.submit();
	}

	function fuoriRintA(obj) {
		var o1 = document.getElementById("tr_" + obj.value + "_1");
		var o2 = document.getElementById("tr_" + obj.value + "_2");
		var o3 = document.getElementById("tr_" + obj.value + "_3");
		if (obj.checked && (o2.checked || o3.checked)) {
			document.getElementById('afr_' + obj.value).style.visibility = 'visible';
		} else {
			document.getElementById('afr_' + obj.value).style.visibility = 'hidden';
		}	
	}

	function fuoriRintR(obj) {
		var key = obj.name.substring(3, obj.name.length);
		var chkBox = document.getElementById("ta_" + key);

		if (chkBox.checked && (obj.value == 'A' || obj.value == 'X')) {
			document.getElementById('afr_' + key).style.visibility = 'visible';
		} else {
			document.getElementById('afr_' + key).style.visibility = 'hidden';
		}				
	}

	var sel=new Array()

	function MemMulti(ss){
		sel.length=0
		for(var i=0;i<ss.options.length;i++)
			if(ss.options[i].selected)
				sel[sel.length]=i
	}

	function SelMulti(ss){
		var ultimo='nessuno'
		for(var i=0;i<ss.options.length;i++)
			if(ss.options[i].selected)
				ultimo=i
		for(i=0;i<ss.options.length;i++)
			ss.options[i].selected=false
		for(i=0;i<sel.length;i++)
			ss.options[sel[i]].selected=true
		if(ultimo!='nessuno')
			ss.options[ultimo].selected=!ss.options[ultimo].selected
	}			
</script>

<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<tr>
		<td class="cmd1" align="left" valign='top'><?=$sCmdL?></td>
		<td class="cmd1" align="right"><?=$sCmdR?></td>
	</tr>
</table>

<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
<?=getHtmlRigaRif();?>
	<tr>
		<td class="tit1" colspan='20' align='center'>Modifica Commessa</td>
	</tr>
    <tr>
   	<td class="lab1" colspan='3'>Codice</td>
	  	<td class="txt1" colspan='7'><?=getHtmlText('cod_comm',40,32);?></td>
   	<td class="lab1" colspan='3'>Cod. Co.Ge.</td>
	  	<td class="txt1" colspan='7'><?=getHtmlText('cod_coge',10,5);?></td>
    </tr>
    <tr>
   	  	<td class="lab1" colspan='3'>Descrizione</td>
	  	<td class="txt1" colspan='17'><?=getHtmlText('descr',128,80);?></td>
    </tr>
    <tr>
      	<td class="lab1" colspan='3'>Data Inizio</td>
	  	<td class="txt1" colspan='7'><?=getHtmlDate('data_iniz');?></td>
      	<td class="lab1" colspan='3'>Data Fine</td>
	  	<td class="txt1" colspan='7'><?=getHtmlDate('data_fine');?></td>   
    </tr>
    <tr>	  
      	<td class="lab1" colspan='3'>Responsabile</td>
	  	<td class="txt1" colspan='7'><?=getHtmlSelect('id_responsabile',$aResp);?></td>
      	<td class="lab1" colspan='3'>Cliente no-rint</td>
	  	<td class="txt1" colspan='7'><?=getHtmlSelect('id_cliente',$aCl);?></td>	  	  
    </tr>
    <tr>
    	<td class="lab1" colspan='3'>Tipo attivita'</td>
    	<td class="txt1" colspan='17'>
    	<?php
			if (count($aTipiAttRint) > 0) {
    			echo  "<table class='tab1' border='0' cellpadding='0' cellspacing='0'>";
    			   
    			foreach ($aTipiAttRint as $key => $value) {
	    			echo "<tr>";
	    			echo "<td class='txt1' valign='top'>".getHtmlCheckBox('ta_'.$key, $key, '@REQ', $aTaOpt)." ".$value['des']."</td>";
	    			echo "<td class='txt1' valign='top'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>";
	    			echo "<td class='txt1' valign='top'>".getHtmlRadio('tr_'.$key, $aTipoRilevazione, '@REQ', $aTrOpt)."</td>";
	    			echo "<td class='txt1'>";
	    				    			
	    			if (isset($aAss[$key])) {
		    			foreach ($aAss[$key] as $ope) {
		    				echo $aUtentiRint[$ope]['nome']."</br> ";
		    			}
	    			}
	    			
	    			echo "</td>";
	    			echo "<td class='txt1' name='afr_".$key."' id='afr_".$key."' valign='top'";
	    			if (reqVar('ta_'.$key) != '' and (reqVar('tr_'.$key) == 'A' or 
	    			                                  reqVar('tr_'.$key) == 'X')) {
	    				echo " style='visibility:visibility;'>";
	    			} else {
	    				echo " style='visibility:hidden;'>";
	    			}
	    					    			
	    			if (reqVar('azione') == 'assFuoriRint' and $key ==  reqVar('ta_fr')) {
	    				echo "<table class='tab1' border='0' cellpadding='0' cellspacing='0'>";
	    				echo "<tr><td class='txt1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>";
	    				echo "<td class='txt1'>";
	    				echo "<select class='inp1' name='ofr[]' SIZE = '4' MULTIPLE onclick='MemMulti(this)' onchange='SelMulti(this)'>";
				    		foreach ($aOpe as $ope => $des) {
				    			echo "<option value='".htmlentities($ope)."' ";
				    			if (isset($_REQUEST['ofr']) and in_array($ope, $_REQUEST['ofr'])) {echo "selected";}				    			
				    			echo ">".htmlentities($des)."</option>";
				    		}
			    		echo "</select>";
			    		echo "</td><td class='txt1' align='center'>";
			    		echo "seleziona operatori e </br>";
			    		echo "<a class='cmd1' href='#' onclick='javascript:submAzione(\"assegnazioneFuoriRint\")'>conferma</a> o ";
			    		echo "<a class='cmd1' href='#' onclick='document.frm1.submit();'>annulla</a>";
			    		echo "</td></tr>";
			    		echo "</table>";
			    		
		    		} else {		    			
		    			echo "   <a class='cmd1' href=\"javascript:submFuoriRint('assFuoriRint', '".$key."');\"> 	
			    				  	assegna tipo attivita' fuori rint
			    				  </a>";
		    					    			
		    		}
		    				  
		    		echo "</td>
	    				  </tr>";
	    		}	    		
	    		echo "</table>";
			}
    	?>    	
    	</td>
    </tr>
    <tr>
    	<td class="lab1" colspan='3'>Richiedenti</td>
    	<td class="txt1" colspan='7' valign='top'>
    	<?  if (count($aRic) > 0) {
    			echo  "<table class='tab1' border='0' cellpadding='0' cellspacing='0'>";
   
	    		foreach ($aRic as $key => $desc) {
	    			echo "<tr>";
	    			echo "<td class='txt1'>".getHtmlCheckBox('rc_'.$key, $key)." ".$desc."</td>";
	    		    echo "</tr>";
	    		}
	    		
	    		echo "</table>";
			} ?>
    	</td>    	
    	<td class="lab1" colspan='3'>Clienti rint</td>
    	<td class="txt1" colspan='7' valign='top'>
    	<?  if (count($aCl) > 1) {
    			echo  "<table class='tab1' border='0' cellpadding='0' cellspacing='0'>";
   
	    		foreach ($aCl as $key => $desc) {
	    			if ($key == 0) {continue;}
	    			echo "<tr>";
	    			echo "<td class='txt1'>".getHtmlCheckBox('cl_'.$key, $key)." ".$desc."</td>";
	    		    echo "</tr>";
	    		}
	    		
	    		echo "</table>";
			} ?>
    	</td>
    </tr>
</table>

<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<tr>
		<td class="cmd1" align="left" valign='top'><?=$sCmdL?></td>
		<td class="cmd1" align="right"><?=$sCmdR?></td>
	</tr>
</table>

<?

echo "</form>\n";

codaHtml();
exit();

function confComm($aTipiAttRint, $aAss, $aRic, $aCl) {
	global $objDB, $objSess;
	
	$msg = '';
	$_REQUEST['cod_comm'] = strtoupper(trim(reqVar('cod_comm')));
	$_REQUEST['cod_coge'] = strtoupper(trim(reqVar('cod_coge')));
	
	if (trim(reqVar('cod_comm'))=="") {
		$msg .= "codice obbligatorio<br>";
	} else {
		// verifica unicita' cod. commessa.
		$strCodUnico = " SELECT id_comm FROM commessa ".
					   " WHERE cod_comm = '".trim(reqVar('cod_comm'))."' AND id_comm != ".intval(reqVar('id'));
		$objDB->query($strCodUnico,'strCodUnico');
		$nRCod = $objDB->numRec('strCodUnico');
		if ($nRCod > 0) {$msg .= "codice gia' esistente<br>";}
	}	
	
	if (trim(reqVar('cod_coge'))=="") {$msg .= "cod. Co.Ge. obbligatorio<br>";}
	if (trim(reqVar('descr'))=="") {$msg .= "descrizione obbligatoria<br>";}
	
	$odx = new rint2Date();
	if ($odx->setDMY(reqVar('data_iniz'))) {
			$dataIniz = $odx->getYMD();
	} else {
			$msg .= "data inizio ".reqVar('data_iniz')." errata <br>";
	}
	
	if ($odx->setDMY(reqVar('data_fine'))) {
			$dataFine = $odx->getYMD();
	} else {
			$msg .= "data fine ".reqVar('data_fine')." errata <br>";
	}
		
	if (trim(reqVar('id_responsabile')) == '0') {$msg .= "responsabile obbligatorio<br>";}

	$clienteObbl = false;
	$clienteRintObbl = false;
	foreach ($aTipiAttRint as $key => $value) {
		if (reqVar('ta_'.$key) != '') {		
			if (reqVar('tr_'.$key) == 'X') {
				$clienteObbl = true;
				$clienteRintObbl = true;
			} else if (reqVar('tr_'.$key) == 'A') {
				$clienteObbl = true;
			} else {
				$clienteRintObbl = true;
			}		
		}	
	}
	
	if (trim(reqVar('id_cliente')) == '0' and $clienteObbl) {$msg .= "cliente obbligatorio<br>";}
	
	$ncl = 0;
	foreach ($_POST as $key => $value) {
		if (substr($key, 0, 2) != "cl") {continue;}
		$ncl ++;
	}
	
	if ($ncl == 0 and $clienteRintObbl) {$msg .= "scegliere almeno un cliente rint<br>";}
	
	if ($msg != '') {return $msg;}

	// modifico commessa.	
	$sSqlUpd = " UPDATE commessa SET ". 
			   "   cod_comm       = '".reqVarAS('cod_comm')."'".
			   ",  cod_coge       = '".reqVarAS('cod_coge')."'".
			   ",     descr       = '".reqVarAS('descr')."'".
			   ", data_iniz       = '".$dataIniz."'".
			   ", data_fine       = '".$dataFine."'".
	           ", id_cliente      = ".reqVar('id_cliente').
			   ", id_responsabile = ".reqVar('id_responsabile').
		       " WHERE id_comm = ".intval(reqVar('id'));	
	$objDB->exec($sSqlUpd);

	// elimino attivita' previste precedenti.
	$sSqlDel = "DELETE FROM att_previste WHERE id_comm = ".intval(reqVar('id'))." AND id_rint = 0";
	$objDB->exec($sSqlDel);
		
	// inserisco le nuove attivita' previste
	foreach ($aTipiAttRint as $key => $value) {
		if (reqVar('ta_'.$key) != '') {
			$sSqlAttPrev = " INSERT INTO att_previste SET ".
		                   "       id_comm = ".intval(reqVar('id'))." ".
		                   ",      id_rint = 0 ".
		                   ",     tipo_att = ".$key.
		                   ", tipo_rilevazione = '".reqVar('tr_'.$key)."' ".
						   ",        stima = 0";
			$objDB->exec($sSqlAttPrev);
		}	
	}	

// elimino le assegnazioni fuori rint per i tipi attivita' non confermati
// o marcati R (solo per rint).	
	foreach ($aAss as $value) {
		if (reqVar('ta_'.$value) == '' or (reqVar('ta_'.$value) != '' and 
		                                   reqVar('tr_'.$value) == 'R')) {

			$sDelAss = " DELETE FROM assegnaz ". 
			           " WHERE id_comm = ".intval(reqVar('id')). 
			           " AND id_rint = 0 ".
					   " AND tipo_att = ".intval($value);	
			$objDB->exec($sDelAss);
		}
	}

// eliminazione richiedenti.	
	$sDelRich = "DELETE FROM richiedenti WHERE id_comm = ".intval(reqVar('id'));
	$objDB->exec($sDelRich);
	
// inserimento nuovi richiedenti.	
	foreach ($aRic as $key => $value) {
		if (reqVar('rc_'.$key) != '') {
			$sInsRic = " INSERT INTO richiedenti SET ".
		               "       id_comm = ".intval(reqVar('id'))." ".
		               ", id_operatore = ".reqVar('rc_'.$key);
			$objDB->exec($sInsRic);
		}	
	}

//  eliminazione clienti.	
	$sDelCli = "DELETE FROM clienti_comm WHERE id_comm = ".intval(reqVar('id'));
	$objDB->exec($sDelCli);
	
//  inserimento nuovi clienti.	
	foreach ($aCl as $key => $value) {
		if ($key == 0) {continue;}
		if (reqVar('cl_'.$key) != '') {
			$sInsCli = " INSERT INTO clienti_comm SET ".
		               "       id_comm = ".intval(reqVar('id'))." ".
		               ", id_cliente = ".reqVar('cl_'.$key);
			$objDB->exec($sInsCli);
		}	
	}

	header("Location: ".urlTorna());
	exit();
}

function confAss() {
	global $objDB, $objSess;
	
	// eliminazione assegnazioni precedenti.
	$sDel = " DELETE FROM assegnaz WHERE id_comm  = ".intval(reqVar('id')).
	        "                        AND id_rint  = 0 ".
	        "                        AND tipo_att = ".intval(reqVar('ta_fr'));
	$objDB->exec($sDel);
	
	// inserimento nuove assegnazioni.
	if (isset($_REQUEST['ofr'])) {
		foreach ($_REQUEST['ofr'] as $ope) {
			$sIns = " INSERT INTO assegnaz SET ".	
			        "  id_comm = ".intval(reqVar('id')).
		            ", id_rint = 0 ".
			        ", tipo_att = ".intval(reqVar('ta_fr')).
				    ", id_operatore = ".intval($ope);		
			$objDB->exec($sIns);
		}
	}	
}
?>




